import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import login from "@/views/login/login.vue";
import { useInfoApi } from "@/api/fetch";
import { usePinia } from "@/store/index";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: login,
  },
  {
    path: "/",
    redirect: "/index",
  },
  //   {
  //     path: "/ums",
  //     component: () => import("../views/home/index.vue"),
  //     children: [
  //       {
  //         path: "admin",
  //         component: login,
  //       },
  //     ],
  //   },
  {
    path: "/",
    component: () => import("../views/home/index.vue"),
    children: [
      {
        path: "index",
        component: () => import("../views/index/index.vue"),
      },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});
// 导航守卫
router.beforeEach((to, from, next) => {
  const useStore = usePinia();
  let token = localStorage.getItem("token");
  if (useStore.menus.length === 0 && token) {
    useInfoApi().then((res) => {
      if (res.code === 200) {
        // 存菜单
        useStore.menus = res.data.menus;
        //存用户民
        useStore.username = res.data.username;
        //   生成当前用户能访问的路由
        useStore.routes.forEach((p) => {
          const route:RouteRecordRaw = {
            path: "/" + p.name,
            name: p.name,
            component: () => import("../views/home/index.vue"),
            meta: {
              title: p.title,
            },
            // redirect: `/${p.name}/${p.children[0]?.name}`,
            children: p.children.map((item) => ({
              path: item.name,
              name: item.name,
              component: () => import(`../views/${p.name}/${item.name}.vue`),
              meta: {
                title: item.title,
              },
            })),
          };
          // 当访问一级路由时跳转到一级子路由
          if (p.children[0]) {
            route.redirect=`/${p.name}/${p.children[0]?.name}`
          }
          router.addRoute(route)
        });
        // path不带参数
        // fullPath带参数
        next(to.fullPath);
      }
    });
    // 判断无token
  } else if (!token && to.path !== "/login") {
    ElMessage.error("请先登录");
    next("/login");
  } else if (token && useStore.menus.length !== 0 && to.path === "/login") {
    // 如果已经登录，不能通过url回到登录页
    // 不让用户访问登录页，跳过回原来的页面
    ElMessage.warning("请先退出登录");
    next(from.fullPath);
  } else {
    next();
  }
});
export default router;
